package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        StringBuffer url = request.getRequestURL();
        String uri = request.getRequestURI();
        log.info("url:{},uri:{}",url,uri);
        if (uri.equals("/login")){
            filterChain.doFilter(request,response);
            //因为方法执行完还会回到这里
            return;
        }
        //获取请求头token
        String token = request.getHeader("Token");
        if (!StringUtils.hasText(token)){
            //响应401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //放行
        filterChain.doFilter(request,response);
    }
}
